<template>
	<view class="content-box">

		<view class="boxs" v-if="listData.length>0">
			<view v-for="(item,index) in listData" :key="index" @click="handlePage1(item)" class="navboxs">
				<view class="navtitle">
					{{item.textPerformanceName}}
				</view>
				<view class="jinri">
					今日:{{item.performanceContent}}
				</view>
				<view class="jinri">
					累计:{{item.completeStatus}}
				</view>
				<view class="jinri">
					个人总目标:{{item.jzzxDailyGoal.personGoal}}
				</view>
				<view class="jinri">
					总目标:{{item.jzzxDailyGoal.overallGoal}}
				</view>

			</view>

		</view>
		<!-- 暂无数据 -->
		<u-empty v-else-if="!isLoading && !refreshing" text="暂无数据" mode="list" margin-top="200rpx"></u-empty>

		<!-- 加载状态 -->
		<u-loadmore :status="loadStatus" :loading-text="loadText" margin-top="20rpx" margin-bottom="40rpx"
			@click="retryLoad"></u-loadmore>
		<!-- 按钮 -->
		<view class="xuanfuboxs">
			<view class="tbyj d-flex j-s-c a-item-c flex-d-c" @click="handleShowpop(true)">
				<view>填补</view>
				<view>业绩</view>
			</view>
			<view @click="handleShowpop(false)" class="hbyjblue d-flex j-s-c a-item-c flex-d-c">
				<view>汇报</view>
				<view>业绩</view>
			</view>
		</view>
		<!-- 弹窗 -->
		<u-popup @close="close" :show="showpop" :closeable="closeable" :closeOnClickOverlay="closeable" mode="center"
			:round="10" zIndex="999" :overlayStyle="{'z-index':99}">
			<view class="popnoxssty">
				<view class="poptitle">
					业绩上报
				</view>
				<view class="time d-flex j-s-c a-item-c" @click="showDatePicker = true" v-if="showStatusPicker">
					选择补填时间：
					<view>
						{{selectedDate}}
					</view>
					<!-- <input type="text" disabled="" v-model="selectedDate" placeholder="请选择补填时间" /> -->

				</view>
				<scroll-view scroll-y="true" class="scroll-box">
					<template v-for="item2 in sbzb">
						<view class="scboxs">
							{{item2.title}}
						</view>
						<view class="inpboxs" @click="handlePage(item2)">
							<!-- <input class="inpsty danwei" type="text" disabled placeholder="请上报填写"> -->
							<view class="danwei">
								{{item2.performanceContent}} {{item2.unit}}
							</view>
							<!-- <view class="danwei inpsty" v-else>
								{{item2.placeholder}}
							</view> -->
						</view>
					</template>
				</scroll-view>

				<view class="save-box">
					<view class="scroll-indicator">
						<view class="text">向下滑动</view>
						<view class="arrow"></view>
					</view>
				</view>
			</view>
		</u-popup>

		<!-- 日期选择弹窗 -->
		<u-datetime-picker :show="showDatePicker" v-model="dateValue" mode="date" :minDate="minDate" :maxDate="maxDate"
			:formatter="formatter" @confirm="onDateConfirm" @cancel="showDatePicker = false" title="选择日期"
			confirmColor="#2585f5"></u-datetime-picker>
	</view>
</template>

<script>
	import {
		businessModules
	} from '@/common/dataList.js'
	import {
		selectPerformance
	} from '@/common/api/renwu.js'
	export default {
		data() {
			const now = new Date();
			const year = now.getFullYear();
			const month = now.getMonth() + 1;
			const day = now.getDate();
			return {
				pageType: "1",
				closeable: true,
				showpop: false,
				// 上报指标
				sbzb: businessModules,

				// 列表数据
				listData: [],
				listData2: [],

				// 分页参数
				pageNum: 1, // 当前页码
				pageSize: 10, // 每页条数
				total: 0, // 总条数

				// 状态控制
				isLoading: false, // 加载中锁
				isFirstLoading: true, // 首次加载状态
				loadStatus: 'loadmore', // 加载状态（loadmore/loading/noMore/error）
				loadText: '上拉加载更多',
				refreshing: false, // 下拉刷新中

				// 筛选相关
				showDatePicker: false,
				showStatusPicker: false,
				selectedDate: '',
				selectedStatus: '',
				dateValue: Number(new Date()),
				minDate: Number(new Date(year - 1, 0, 1)),
				maxDate: Number(new Date(year, 11, 31)),
				nowDate: `${year}-${month}-${day}`
			}
		},
		onLoad(res) {
			this.pageType = res.id
			if (res.id == '1') {
				uni.setNavigationBarTitle({
					title: '业务上报'
				});
			} else if (res.id == '2') {
				uni.setNavigationBarTitle({
					title: '业绩上报'
				});
			}
		},
		onShow() {
			this.reset()
			this.queryList()
		},
		methods: {
			handleShowpop(status) {
				this.showStatusPicker = status;
				this.showpop = true
				this.selectedDate = this.nowDate
				console.log(this.selectedDate)
				// 拼接时间（例如 00:00:00）
				// const fullDateStr = `${this.selectedDate} 00:00:00`;

				// // 转换为时间戳
				// const timestamp = new Date(fullDateStr);
				this.queryDateList(this.selectedDate)
			},
			// 日期格式化
			formatter(type, value) {
				if (type === 'year') return `${value}`;
				if (type === 'month') return `${value}`;
				if (type === 'day') return `${value}`;
				return value;
			},

			// 日期筛选确认
			onDateConfirm(e) {
				this.selectedDate = this.$formatTime(e.value,'YYYY-MM-DD')

				this.showDatePicker = false;
				this.queryDateList(this.selectedDate)

			},
			reset() {
				this.loadStatus = 'loading';
				this.loadText = '加载中...';
				this.isLoading = false;
				this.listData = [];
				this.pageNum = 1
			},
			close() {
				this.showpop = false
				this.selectedDate = ''
				// console.log('close');
			},
			// 跳转详情
			handlePage(item) {
				if (item.id && !this.showStatusPicker) {
					uni.showToast({
						title: '今日已填写',
						icon: 'none'
					})
					return false;
				}
				let url =
					`/homeNav/rwgl/yjhb/yjhb?type=0&b_id=${item.b_id}&title=${item.title}&unit=${item.unit}&reportingTime=${this.selectedDate}`
				if (item.id && this.showStatusPicker) { // 补填
					url =
						`/homeNav/rwgl/yjhb/yjhb?type=0&b_id=${item.b_id}&title=${item.title}&unit=${item.unit}&id=${item.id}&reportingTime=${this.selectedDate}`
				}
				uni.navigateTo({
					url: url, //type=0 业绩汇报
					// success: function(res) {
					// 	// 通过eventChannel向被打开页面传送数据
					// 	res.eventChannel.emit('acceptDataFromOpenerPage', item)
					// }
				})
			},
			handlePage1(item) {
				uni.navigateTo({
					url: '/homeNav/rwgl/yjhb/yjhb_detail?id=' + item.id
				})
			},
			// 查询列表
			async queryList() {
				if (this.isLoading) return;
				this.isLoading = true;
				this.loadStatus = 'loading';
				this.loadText = '加载中...';
				try {
					await selectPerformance({
						sourceType: 1,
						pageNum: this.pageNum,
						pageSize: this.pageSize
					}).then((res) => {
						console.log(res, '========')
						this.isLoading = false;
						this.total = res.data.total;
						this.listData = [...this.listData, ...res.data.records];
						if (this.listData.length >= this.total) {
							this.loadStatus = 'noMore';
							this.loadText = '已加载全部数据';
						} else {
							this.loadStatus = 'loadmore';
							this.loadText = '上拉加载更多';
							this.pageNum++; // 页码自增
						}
					})

				} catch (error) {
					this.isLoading = false;
					this.loadStatus = 'error';
					this.loadText = '加载失败，点击重试';
					//TODO handle the exception
				}
			},

			// 弹框-查询当天(或者筛选时间)填报业绩
			async queryDateList(timeSearch) {
				console.log(timeSearch, 'timeSearch')
				try {
					await selectPerformance({
						sourceType: 1,
						timeSearch: timeSearch,
						pageNum: 1,
						pageSize: 100
					}).then((res) => {
						this.listData2 = res.data.records;
						console.log(res.data.records)
						// console.log(this.sbzb)
						this.matchedAList(res.data.records, this.sbzb)
					})
				} catch (error) {

				}
			},
			// 回显-匹配
			matchedAList(a, b) {
				console.log(b, '--bb')
				const needMergeFields = [
					'performanceContent', // 绩效内容
					'id',
				];
				const result = a.length === 0 ?
					b.map(item => ({
						...item,
						id: '',
						performanceContent: '' // 强制清空该字段（无论是否存在）
					})) :
					b.map(bItem => {
						const bIdStr = String(bItem.b_id);
						const matchedA = a.find(aItem => aItem.performanceName === bIdStr);

						if (matchedA) {
							const aFieldsToMerge = {};
							needMergeFields.forEach(field => {
								aFieldsToMerge[field] = matchedA[field];
							});
							return {
								...bItem,
								...aFieldsToMerge
							};
						} else {
							return bItem; // 未匹配到，返回 b 原元素
						}
					});
				this.sbzb = result
			}
		},
		// 页面触底时触发（UniApp 自带生命周期）
		onReachBottom() {
			console.log('cccc')
			// 触底加载更多（排除首次加载、正在加载、无更多数据的情况）
			if (!this.isLoading && this.loadStatus === 'loadmore') {
				console.log('22')
				this.queryList();
			}
		},
	}
</script>

<style scoped lang="scss">
	.boxs {
		width: 100%;
		// min-height: 100vh;
		display: flex;
		flex-flow: row wrap;
		// align-items: center;


	}

	// .empty{
	// 	width: 400rpx;
	// 	height: 400rpx;
	// }
	// justify-content: space-between;
	.navboxs {
		width: 42%;
		margin-left: 40rpx;
		background-color: #ffffff;
		margin-top: 40rpx;
		padding-bottom: 25rpx;
		box-shadow:
			3px 2px 4px rgba(0, 0, 0, 0.2),
			-2px 2px 3px rgba(0, 0, 0, 0.1);

		.navtitle {
			// font-weight: bold;
			font-size: 28rpx;
			margin-top: 20rpx;
			margin-left: 20rpx;

		}

		.jinri {
			font-size: 26rpx;
			margin-top: 10rpx;
			margin-left: 20rpx;
			color: #999999;
		}
	}

	.xuanfuboxs {
		// width: 120rpx;
		position: fixed;
		z-index: 100;
		bottom: 60rpx;
		right: 10rpx;

		.tbyj {
			background-color: #999999;
			color: white;
			border-radius: 50%;
			width: 90rpx;
			height: 90rpx;
			padding: 13rpx;
			text-align: center;
		}

		.hbyjred {
			background-color: #a31010;
			color: white;
			border-radius: 50%;
			width: 90rpx;
			height: 90rpx;
			padding: 13rpx;
			text-align: center;
			margin-top: 20rpx;
		}

		.hbyjblue {
			background-color: #2585f5;
			color: white;
			border-radius: 50%;
			width: 90rpx;
			height: 90rpx;
			padding: 13rpx;
			text-align: center;
			margin-top: 20rpx;
		}
	}

	.popnoxssty {
		width: 660rpx;
		// padding-bottom: 60rpx;
		z-index: 1000;

		.scroll-box {
			height: 60vh;
		}

		.poptitle {
			text-align: center;
			margin-top: 30rpx;
		}

		.scboxs {
			margin-top: 20rpx;
			margin-left: 60rpx;
		}

		.inpboxs {
			width: 82%;
			margin-left: 9%;
			border: 1px solid #999999;
			display: flex;
			align-items: center;
			justify-content: space-between;
			margin-top: 10rpx;

			.inpsty {
				color: #999;
			}

			.danwei {
				width: 100%;
				min-height: 60rpx;
				line-height: 60rpx;
				text-align: right;
				margin-right: 20rpx;
			}
		}
	}

	.save-box {
		// background-color: #2585f5;
		// color: #ffffff;
		// width: 60%;
		margin: 20rpx auto;
		text-align: center;
		// padding: 20rpx 0;
		border-radius: 16rpx;
	}

	.time {
		text-align: center;
		margin: 10px 0 0;
		color: #666;
	}

	::v-deep .u-popup__content__close {
		z-index: 1000;
	}
	
	/* 下滑提示样式 */
	.scroll-indicator {
		// position: absolute;
		// bottom: 30px;
		// left: 50%;
		// transform: translateX(-50%);
		z-index: 1000;
		text-align: center;
		animation: float 2s ease-in-out infinite;
		opacity: 0.8;
		transition: opacity 0.3s;
	}
	
	.scroll-indicator:hover {
		opacity: 1;
	}
	
	.scroll-indicator .text {
		font-size: 0.9rem;
		color: #555;
		// margin-bottom: 5px;
		font-weight: 500;
	}
	
	.scroll-indicator .arrow {
		width: 20rpx;
		height: 20rpx;
		border-right: 2px solid #3498db;
		border-bottom: 2px solid #3498db;
		transform: rotate(45deg);
		margin: 0 auto;
	}
	
	/* 浮动动画 */
	@keyframes float {
	
		0%,
		100% {
			transform: translateX(0%) translateY(0);
		}
	
		50% {
			transform: translateX(0%) translateY(-10px);
		}
	}
</style>